#'###########################################
#'                                          #
#'  ------------------------------------    #
#'  |     COIN     __                  |    #
#'  |            >(' )                 |    #
#'  |              )/                  |    #
#'  |             /  `----/            |    #
#'  |             \  ~=- /             |    #
#'  |   ~^~^~^~^~^~^~^~^~^~^~^~^~^~^   |    #
#'  ------------------------------------    #
#'                                          #
#'###########################################

rm(list=ls())
rm(.Random.seed)
loadfonts(device = "postscript")

#'#
#'# Chemins de travail
#'#
R_ROOT <- "C:/UQAR/Recherche/Maitrise/Donnees"
R_WORKING_DIRECTORY <- file.path(R_ROOT, "R")
R_DATA_PATH <- file.path(R_ROOT, "Donnees")
R_RESULTS_PATH <- file.path(R_ROOT, "Resultats")

R_STATIC_DIR <- file.path(R_DATA_PATH, "Bylot/Fixe")
R_MOBILE_DIR <- file.path(R_DATA_PATH, "Bylot/Mobile")

DATA_PATH <- file.path(R_RESULTS_PATH, "HRCompare")


#'#
#'# Chargement des dependances
#'# 

#source(file.path(R_WORKING_DIRECTORY, "Utils/initCluster.R"))
source(file.path(R_WORKING_DIRECTORY, "Utils/loadDependencies.R"))


#'#
#'# Chargement des donnees
#'# 

#' hrGraphsTracksAll
load(file.path(DATA_PATH, "hrGraphsTracksAll.RData"))
hrGraphsTracksAll[, type := factor(type, levels=c("Ref", "Raw", "LC32", "LC321",
            "DAF","SF", "TrStat", "TrMob"))]
levels(hrGraphsTracksAll$type) <- c("Ref", "Raw", "LC32", "LC321",
    "DAF","HSF", "Static", "Mobile")
filters <- c("Ref", "Raw", "LC32", "LC321", "DAF","HSF")
simulations <- c("Static", "Mobile")
    
hrGraphsTracksAll95 <-  hrGraphsTracksAll[percent == 95]

cols <- grey(c(0.8, 0.4))
cex.scales <- 0.9
cex.label <- 1.1
xlabels <- c("250", "500", "750", "1000", "2500", "5000")

#'#
#'# Comparaison de la taille
#'# 
hrComparedArea <- hrGraphsTracksAll95[stat == "comparedArea"]
hrComparedArea[, mean := mean / 1000000]
hrComparedArea[, li := li / 1000000]
hrComparedArea[, ls := ls / 1000000]

hrComparedAreaFilters <- hrComparedArea[type %in% filters]
hrComparedAreaSimulations <- hrComparedArea[type %in% simulations]

gSize95a <- barchart(mean ~ type, data=hrComparedAreaFilters, groups=method, col=cols,
    scales =list(col=1, tck=c(1,0), cex=cex.scales, axs = "i"),
    origin = 0,
    ly=hrComparedAreaFilters$li,
    uy=hrComparedAreaFilters$ls,
    par.settings = list(axis.line = list(col="transparent"),
      layout.widths = list(left.padding=2, right.padding = 0)),
    prepanel=prepanel.errorbar, panel=panel.errorbar,
    addText=TRUE,
    textFUN=panel.text.title,
    text.title="Observed",
    text.letter="A",
    ylab=list(expression(bold(paste("Home range size (", km^2, " \261 95% CI)", sep=""))), cex=cex.label, fontface="bold")
)
gSize95b <- barchart(mean ~ type, data=hrComparedAreaSimulations, groups=method, col=cols,
    scales =list(y=list(draw=FALSE), col=1, tck=c(0,0), cex=cex.scales, axs = "i"),#, alternating=2),
    origin = 0, ylimits=gSize95a$y.limits,
    ly=hrComparedAreaSimulations$li,
    uy=hrComparedAreaSimulations$ls,
    par.settings = list(axis.line = list(col="transparent"),
                        layout.widths =
                          list(left.padding = 0,
                          key.ylab.padding = 0,
                          ylab.axis.padding = 0,
                          axis.key.padding = 0,
                          right.padding = 1)),
    addText=TRUE,
    textFUN=panel.text.title,
    text.title="Simulated",
    text.x=0.15,
    prepanel=prepanel.errorbar, panel=panel.errorbar,
    draw.yaxis=FALSE,
    #axis.right = TRUE,
    ylab=NULL
)

#'#
#'# Comparaison des ratios de taille
#'# 
hrSizeRatio <- hrGraphsTracksAll95[stat == "sizeRatio"]

hrSizeRatioFilters <- hrSizeRatio[type %in% filters]
hrSizeRatioSimulations <- hrSizeRatio[type %in% simulations]

gSizeRatio95a  <- barchart(mean ~ type, data=hrSizeRatioFilters, groups=method, col=cols,
    scales =list(col=1, tck=c(1,0), cex=cex.scales, axs = "i", y=list(at=c(0, 1, 5, 10 ,15))),
    origin = 0,
    ly=hrSizeRatioFilters$li,
    uy=hrSizeRatioFilters$ls,
    par.settings = list(axis.line = list(col="transparent"),
        layout.widths = list(left.padding=0, right.padding = 0)),
    prepanel=prepanel.errorbar, panel=panel.errorbar,
    addText=TRUE,
    textFUN=panel.text.title,
    text.title="Observed",
    text.letter="B",
    ylab=list("Size ratio Argos to GPS (\261 95% CI)", cex=cex.label, fontface="bold")
)
gSizeRatio95a <- gSizeRatio95a + layer(panel.abline(h=1, lty=2))

gSizeRatio95b <- barchart(mean ~ type, data=hrSizeRatioSimulations, groups=method, col=cols,
    scales =list(y=list(draw=FALSE), col=1, tck=c(0,1), cex=cex.scales, axs = "i"),
    origin = 0, ylimits=gSizeRatio95a$y.limits,
    ly=hrSizeRatioSimulations$li,
    uy=hrSizeRatioSimulations$ls,
    par.settings = list(axis.line = list(col="transparent"),
        layout.widths =
            list(left.padding = 0,
                key.ylab.padding = 0,
                ylab.axis.padding = 0,
                axis.key.padding = 0,
                right.padding = 1)),
    addText=TRUE,
    textFUN=panel.text.title,
    text.title="Simulated",
    text.x=0.15,
    prepanel=prepanel.errorbar, panel=panel.errorbar,
    draw.yaxis=FALSE,
    ylab=NULL
)
gSizeRatio95b <- gSizeRatio95b + layer(panel.abline(h=1, lty=2))

#'#
#'# Comparaison de la proportion de points dans le DV de reference
#'# 
hrPropInRef <- hrGraphsTracksAll95[stat == "propInRef"]

hrPropInRefFilters <- hrPropInRef[type %in% filters]
hrPropInRefSimulations <- hrPropInRef[type %in% simulations]

gPropInRef95a <- barchart(mean ~ type, data=hrPropInRefFilters, groups=method, col=cols,
    scales =list(col=1, tck=c(1,0), cex=cex.scales, axs = "i"),
    origin = 0,
    ly=hrPropInRefFilters$li,
    uy=hrPropInRefFilters$ls,
    par.settings = list(axis.line = list(col="transparent"),
        layout.widths = list(left.padding=2, right.padding = 0)),
    prepanel=prepanel.errorbar, panel=panel.errorbar,
    addText=TRUE,
    textFUN=panel.text.title,
    text.title="Observed",
    text.letter="C",
    ylab=list("Proportion of Argos locations in GPS HR (% \261 95% CI)", cex=cex.label, fontface="bold")
)
gPropInRef95b <- barchart(mean ~ type, data=hrPropInRefSimulations, groups=method, col=cols,
    scales =list(y=list(draw=FALSE), col=1, tck=c(0,1), cex=cex.scales, axs = "i"),
    origin = 0, ylimits=gPropInRef95a$y.limits,
    ly=hrPropInRefSimulations$li,
    uy=hrPropInRefSimulations$ls,
    par.settings = list(axis.line = list(col="transparent"),
        layout.widths =
            list(left.padding = 0,
                key.ylab.padding = 0,
                ylab.axis.padding = 0,
                axis.key.padding = 0,
                right.padding = 1)),
    addText=TRUE,
    textFUN=panel.text.title,
    text.title="Simulated",
    text.x=0.15,
    prepanel=prepanel.errorbar, panel=panel.errorbar,
    draw.yaxis=FALSE,
    ylab=NULL
)

#font_import()




## postscript("C:/UQAR/Recherche/Maitrise/Donnees/Resultats/compareHRTracks_final2.eps",
##     width=10, height=10, paper="special", family="Arial", onefile=FALSE,
##     horizontal=FALSE)

#png("C:/UQAR/Recherche/Maitrise/Donnees/Resultats/compareHRTracks10_95.png", 2400, 2400, res=200)

bitmap(file="C:/UQAR/Recherche/Maitrise/Donnees/Resultats/compareHRTracks_final_v4.tiff",
    units='in', res=300, height=12, width=12, type="tiff24nc", pointsize=12, family="Arial")

grid.newpage()
## top <- viewport(layout = grid.layout(2, 5,
##         widths = c(unit(2.5, "inches"), .12, .02, .37, .12), heights = rep(.5, 2)), name="graphs")
top <- viewport(layout = grid.layout(2, 5,
        widths = c(unit(2.6, "inches"), unit(0.8, "inches"),
            unit(0.13, "inches"), unit(2.6, "inches"), unit(0.8, "inches")),
        heights = rep(.5, 2)), name="graphs")
size95a <- viewport(layout.pos.col = 1, layout.pos.row = 1,
    name = "size95a")
size95b <- viewport(layout.pos.col = 2, layout.pos.row = 1,
    name = "size95b")
sizeRatio95a <- viewport(layout.pos.col = 4, layout.pos.row = 1,
    name = "sizeRatio95a")
sizeRatio95b <- viewport(layout.pos.col = 5, layout.pos.row = 1,
    name = "sizeRatio95b")
propInRef95a <- viewport(layout.pos.col = 1, layout.pos.row = 2,
    name = "propInRef95a")
propInRef95b <- viewport(layout.pos.col = 2, layout.pos.row = 2,
    name = "propInRef95b")
legend <- viewport(layout.pos.col = 4, layout.pos.row = 2,
     just=c("left", "top"), name = "legend")
graphs <- vpTree(top, vpList(size95a, size95b, sizeRatio95a, sizeRatio95b, propInRef95a, propInRef95b, legend))

pushViewport(graphs)
seekViewport("graphs")
print(gSize95a, draw.in="size95a")
print(gSize95b, draw.in="size95b")
print(gSizeRatio95a, draw.in="sizeRatio95a")
print(gSizeRatio95b, draw.in="sizeRatio95b")
print(gPropInRef95a, draw.in="propInRef95a")
print(gPropInRef95b, draw.in="propInRef95b")

seekViewport("legend")
  vp1.1 <- viewport(x = 0.3, y = 0.87, 
      height = 0.5, width = 0.5,
      just = "centre",
      name = "legend.key")
  pushViewport(vp1.1)
draw.key(list(text=list(c("Kernel", "MCP")), rectangles=list(col=cols), x=0.5, y=1, 
    corner=c(0.5, 1), cex=1, fontface="bold"), draw=TRUE)
seekViewport("graphs")

#seekViewport("size95a")
#grid.lines(c(0.99, 0.99), c(0.08, 0.95), gp=gpar(lty=2))
#upViewport()
#seekViewport("sizeRatio95a")
#grid.lines(c(0.99, 0.99), c(0.08, 0.95), gp=gpar(lty=2))
#upViewport()
#seekViewport("propInRef95a")
#grid.lines(c(0.99, 0.99), c(0.08, 0.95), gp=gpar(lty=2))
#upViewport()

dev.off()

#showViewport(graphs)


#'#################################################################################################
#'#                                                                                              ##
#'#                                 Comparaison Kernel/MCP                                       ##
#'#                                                                                              ##
#'#################################################################################################


k <- hrGraphsTracksAll95[method=="kernel" & type %in% c("Raw", "LC32", "LC321", "DAF", "SF")]
m <- hrGraphsTracksAll95[method=="mcp" & type %in% c("Raw", "LC32", "LC321", "DAF", "SF")]
k[, ratio := (mean / m$mean)]

ratios <- k[, list(mean=mean(ratio), sd= sd(ratio)), by=stat]

xyplot(ratio ~ type, data=k[stat=="sizeRatio"])
xyplot(ratio ~ type, data=k[stat=="overlapIndex"])
xyplot(ratio ~ type, data=k[stat=="propInRef"])



